package cn.wolfcode.education.service.impl;

import cn.wolfcode.education.domain.*;
import cn.wolfcode.education.domain.Collections;
import cn.wolfcode.education.mapper.ClientMapper;
import cn.wolfcode.education.mapper.CollectionsMapper;
import cn.wolfcode.education.mapper.RegularStuMapper;
import cn.wolfcode.education.mapper.TransferHistoryMapper;
import cn.wolfcode.education.query.ClientQuery;
import cn.wolfcode.education.query.QueryObject;
import cn.wolfcode.education.service.IClientService;
import cn.wolfcode.education.util.PageResult;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class ClientServiceImpl implements IClientService {

    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private RegularStuMapper regularStuMapper;
    @Autowired
    private TransferHistoryMapper transferHistoryMapper;
    @Autowired
    private CollectionsMapper collectionsMapper;

    public PageResult query(ClientQuery qo) {
        int total = clientMapper.queryForCount(qo);
        List<Client> rows = clientMapper.queryForList(qo);
        return new PageResult(total, rows);
    }

    public void save(Client client) {

        isExsists(client.getName());

        Employee currentEmp = (Employee) SecurityUtils.getSubject().getPrincipal();  // 从容器中获取当前登录的用户
        client.setTraceNumber(0L); // 设置跟踪次数

        // 根据用户选择设置初始状态
        SystemDictionaryItem item = new SystemDictionaryItem();
        Boolean isTrace = client.getIsTrace();
        if (isTrace != null) {
            if (isTrace) {
                item.setId(54L);
                client.setAttachEmployee(currentEmp);
            } else {
                item.setId(55L);
            }
        } else {
            item.setId(55L);
        }
        client.setState(item);
        client.setBuildDocTime(new Date()); // 设置建档时间
        client.setInputTime(new Date()); // 设置录入时间
        client.setInputEmployee(currentEmp);//设置录入人,获取当前登录用户
        // 获取到推荐人名字,看是否包含在正式学员里,如果是则设置推荐学员
        String introducer = client.getIntroducer();
        List<Map<Long, Object>> allStu = regularStuMapper.getAllStu();
        for (Map<Long, Object> map : allStu) {
            Set<Map.Entry<Long, Object>> entries = map.entrySet();
            for (Map.Entry<Long, Object> entry : entries) {
                if (introducer.equals(entry.getValue())) {
                    RegularStu stu = new RegularStu();
                    stu.setId(entry.getKey());
                    client.setIntroducerStu(stu);
                }
            }
        }

        isExsists(client.getName());
        clientMapper.save(client);
    }

    public void update(Client client) {
        Employee currentEmp = (Employee) SecurityUtils.getSubject().getPrincipal();  // 从容器中获取当前登录的用户
        SystemDictionaryItem item = new SystemDictionaryItem();
        Boolean isTrace = client.getIsTrace();
        if (isTrace != null) {
            if (isTrace) {
                item.setId(54L);
                client.setAttachEmployee(currentEmp);
            } else {
                item.setId(55L);
                client.setAttachEmployee(null);
            }
        } else {
            item.setId(55L);
        }
        client.setState(item);
        clientMapper.updateByPrimaryKey(client);
    }

    public void clientToPool(Long clientId) {
        // 将客户存入潜在客户池,就是将客户的状态改为待跟踪
        clientMapper.clientToPool(clientId);
    }

    // 获取所有潜在客户
    public List<Client> getTestClient() {
        return clientMapper.getTestClient();
    }


    // 潜在客户转正式学员
    public void formal(RegularStu regularStu) {

        System.out.println(regularStu.getIdNum());
        Long idNum = regularStu.getIdNum();

        System.out.println(idNum);

        System.out.println(regularStu.getWishWork());
        System.out.println(regularStu.getEmergencyName());
        System.out.println(regularStu.getEmergencyTel());
        System.out.println(regularStu.getExperienceWork());


        //计算费用未缴纳的学费
        BigDecimal unPaidFee = regularStu.getTotalFee().subtract(regularStu.getPaidFee());

        // 判断是否已缴费
        int feeStatus = RegularStu.FEE_NO;
        if (unPaidFee.compareTo(new BigDecimal(0)) == 0) {
            feeStatus = RegularStu.FEE_YES;
        }

        // 赋值
        regularStu.setUnPaidFee(unPaidFee);
        // 设置付费状态
        regularStu.setFeeStatus(feeStatus);

        System.out.println(regularStu);

        // 获取当前登录用户
        Employee currentEmp = (Employee) SecurityUtils.getSubject().getPrincipal();
        regularStu.setInputEmployee(currentEmp);
        regularStu.setInputTime(new Date());
        regularStuMapper.insert(regularStu);

        // 设置收款管理,新进学员需要付款
        Collections collections = new Collections();
        collections.setName(regularStu.getName());
        collections.setClassgrade(regularStu.getClassgrade());
        collections.setCollectionMoneyTime(new Date());
        collections.setTotalFee(regularStu.getTotalFee());
        collections.setUnPaidFee(unPaidFee);
        collections.setPaidFee(regularStu.getPaidFee());
        collections.setInputEmployee(currentEmp);
        collections.setPaymentType(regularStu.getPaymentType());
        collections.setPayment(regularStu.getPayment());
        collections.setRegularStuId(regularStu.getId());
        collections.setStatusEmployee(currentEmp);
        collectionsMapper.insert(collections); // 插入一条收款数据

    }

    // 用户入学后将用户在在潜在学员表中删除
    public void removeClient(Long clientId) {
        clientMapper.removeClientById(clientId);
    }

    // 潜在客户池查看
    public PageResult queryClientPool(QueryObject qo) {
        int total = clientMapper.queryCountForPool(qo);
        List<Client> rows = clientMapper.queryListForPool(qo);
        return new PageResult(total, rows);
    }

    // 接手潜在客户
    public void receiveClient(Long clientId) {

        // 获取当前登录用户
        Employee currentEmp = (Employee) SecurityUtils.getSubject().getPrincipal();


        // 获取客户的信息,为了记录移交历史表
        Client client = clientMapper.selectClientById(clientId);
        // new一个transferhistory对象,设置数据
        TransferHistory history = new TransferHistory();
        history.setClient(client); // 设置被移交的客户
        history.setQq(client.getQq()); // 设置qq
        history.setTel(client.getTel()); // 设置tel
        history.setTransferTime(new Date());  // 设置移交时间
        history.setFormerly(client.getAttachEmployee()); // 设置交出人
        history.setNow(currentEmp); // 设置接手人,当前登录用户
        transferHistoryMapper.insert(history);

        // 接手潜在客户,设置客户的状态为已跟进,将客户的归属员工设置为当前操作的用户
        // 在xml中直接操作,将参数传递进去即可
        clientMapper.receiveClient(clientId, currentEmp.getId());
    }

    // 指派潜在客户
    public void appointClient(Long id, Long appointWhoId) {

        // 获取当前登录用户
        Employee currentEmp = (Employee) SecurityUtils.getSubject().getPrincipal();

        // 获取到被指派客户的信息
        Client client = clientMapper.selectClientById(id);

        // new一个transferhistory对象,设置数据
        TransferHistory history = new TransferHistory();
        history.setClient(client);
        history.setQq(client.getQq());
        history.setTel(client.getTel());
        history.setTransferTime(new Date());
        history.setFormerly(client.getAttachEmployee()); // 设置交出人

        Employee employee = new Employee();
        employee.setId(appointWhoId);// 指派给指定人
        history.setNow(employee);// 设置当前接手人
        transferHistoryMapper.insert(history);

        // 接手潜在客户,设置客户的状态为已跟进,将客户的归属员工设置为当前操作的用户
        // 在xml中直接操作,将参数传递进去即可
        clientMapper.receiveClient(id, appointWhoId); // 设置client表中的当前归属和状态
    }

    // 查询某个客户是否存在
    public void isExsists(String clientName) {
        List<Map<String, Object>> maps = clientMapper.isExsists();
        for (Map<String, Object> map : maps) {
            Collection<Object> values = map.values();
            for (Object value : values) {
                if (clientName.equals(value)) {
                    throw new RuntimeException("该客户已经存在,不要重复添加!");
                }
            }
        }
    }

    // 判断客户归属
    public void judge(Long clientId) {
        Employee currentEmp = (Employee) SecurityUtils.getSubject().getPrincipal();
        Client client = clientMapper.judge(clientId);
        if (!currentEmp.getId().equals(client.getAttachEmployee().getId())) {
            throw new RuntimeException("您不是当前客户的归属人,不能进行此操作!");
        }
    }

    public List<Client> queryForList(ClientQuery qo) {
        return clientMapper.queryForList(qo);
    }

}























